import { Injectable } from '@angular/core';
import { AppConfig } from "../config";
import { Http, Headers } from "@angular/http";
import { DatePipe } from "@angular/common";
import { InterceptorService } from "../service/interceptor/interceptor-service";
import { WarmCount } from "../entity/turb-early-warn.model";


@Injectable()
export class EarlyWarnStatisticeService {
  private fomat: string = "yyyy-MM-dd HH:mm:ss";
  private readonly headers = new Headers({
    'Content-Type': 'application/json'
  });
  private readonly param = "reportHisWarns/getWarnCount";
  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(
    private http: InterceptorService,
    private datePipe: DatePipe
  ) { }

  public getWarnCount(deviceIds: number[], startTime: Date, endTime: Date): Promise<WarmCount[]> {

		let startFomat: string = "";
		let endFomat: string = "";

		startFomat = this.datePipe.transform(startTime, this.fomat);
		endFomat = this.datePipe.transform(endTime, this.fomat);

		return this.http.post(this.url, JSON.stringify({ 'deviceIds': deviceIds, 'startTime': startFomat, 'endTime': endFomat }), { headers: this.headers })
			.toPromise()
			.then(response => {
				try {
					let result = response.json();
					switch (result.code) {
						case "200":
							return result.data as WarmCount[];
						case "-1":
							throw new Error(result.message);
					}
				}
				catch (error) {
					throw error;
				}
			})
			.catch(this.handleError);
	}


  private handleError(error: any): Promise<any> {
		return Promise.reject(error.message || error);
	}

}



// WEBPACK FOOTER //
// ./src/app/service/early-warn-statistice.service.ts